﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.WebSockets;
using System.IO;
using System.Windows.Forms;

namespace MESHTTP
{
    public class httpPost
    {
        public static string PostRequest(string url, string content)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);/* as HttpWebRequest;*///创建请求
            byte[] bs = Encoding.UTF8.GetBytes(content);
            string responseData = String.Empty;
            request.Method = "POST";
            request.ContentType = "application/json";
            request.KeepAlive = false;
            try
            {
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                    reqStream.Close();
                }
            }
            catch
            {
                MessageBox.Show("服务器连接不上");
            }
            string result = "";
            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(reader.ReadToEnd());
                result = sb.ToString();
            }
            response.Close();
            return result;
        }
    }
}
